import { useEffect, useRef, useState } from "react";

const CanvasScreenshot = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [screenshotUrl, setScreenshotUrl] = useState<string | undefined>(
    undefined
  );
  const [isDrawing, setIsDrawing] = useState(false);
  const [startPoint, setStartPoint] = useState<{ x: number; y: number } | null>(
    null
  );
  const [endPoint, setEndPoint] = useState<{ x: number; y: number } | null>(
    null
  );
  useEffect(() => {
    initCanvas();
  }, []);

  const initCanvas = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;
    canvas.width = 800;
    canvas.height = 800;
    const img = new Image();
    img.src = "https://picsum.photos/800";
    img.crossOrigin = "anonymous";
    img.onload = () => {
      ctx.drawImage(img, 0, 0);
    };
  };

  const handleMouseDown = (e: React.MouseEvent<HTMLCanvasElement>) => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    setIsDrawing(true);
    setStartPoint({ x, y });
    setEndPoint(null);
  };

  const handleMouseMove = (e: React.MouseEvent<HTMLCanvasElement>) => {
    if (!isDrawing || !startPoint) return;
    const canvas = canvasRef.current;
    if (!canvas) return;
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    setEndPoint({ x, y });
    renderCanvasWithSelection();
  };

  const handleMouseUp = () => {
    setIsDrawing(false);
  };

  const renderCanvasWithSelection = () => {
    const canvas = canvasRef.current;
    if (!canvas || !startPoint || !endPoint) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;
    const img = new Image();
    img.src = "https://picsum.photos/800";
    img.crossOrigin = "anonymous";
    img.onload = () => {
      ctx.drawImage(img, 0, 0);
      const { x: startX, y: startY } = startPoint;
      const { x: endX, y: endY } = endPoint;
      const left = Math.min(startX, endX);
      const top = Math.min(startY, endY);
      const width = Math.abs(endX - startX);
      const height = Math.abs(endY - startY);
      ctx.strokeStyle = "blue";
      ctx.lineWidth = 2;
      ctx.strokeRect(left, top, width, height);
      ctx.fillStyle = "rgba(0,0,255,0.1)";
      ctx.fillRect(left, top, width, height);
    };
  };

  const captureSelection = () => {
    const canvas = canvasRef.current;
    if (!canvas || !startPoint || !endPoint) {
      alert("请先选择截图区域");
      return;
    }
    const { x: startX, y: startY } = startPoint;
    const { x: endX, y: endY } = endPoint;
    const left = Math.min(startX, endX);
    const top = Math.min(startY, endY);
    const width = Math.abs(endX - startX);
    const height = Math.abs(endY - startY);
    if (width === 0 || height === 0) {
      alert("选择区域无效");
      return;
    }
    const tempCanvas = document.createElement("canvas");
    tempCanvas.width = width;
    tempCanvas.height = height;
    const tempCtx = tempCanvas.getContext("2d");
    if (!tempCtx) return;
    const img = new Image();
    img.src = "https://picsum.photos/800";
    img.crossOrigin = "anonymous";
    img.onload = () => {
      const scaleX = canvas.width / img.width;
      const scaleY = canvas.height / img.height;
      const sourceX = left / scaleX;
      const sourceY = top / scaleY;
      const sourceWidth = width / scaleX;
      const sourceHeight = height / scaleY;
      tempCtx.drawImage(
        img,
        sourceX,
        sourceY,
        sourceWidth,
        sourceHeight,
        0,
        0,
        width,
        height
      );
      const url = tempCanvas.toDataURL("image/png");
      setScreenshotUrl(url);
    };
  };

  return (
    <>
      <canvas
        ref={canvasRef}
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
        onMouseLeave={handleMouseUp}
      />
      <button onClick={captureSelection}>截取选择区域</button>
      {screenshotUrl && <img src={screenshotUrl} alt="截图预览" />}
    </>
  );
};

export default CanvasScreenshot;
